package dw.fastfile.common.exception;

import dw.fastfile.common.dto.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @description: 异常处理
 * @author: wanghao
 * @create: 2024-01-31 16:02
 **/
@RestControllerAdvice
@Slf4j
public class ExceptionHandle {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public CommonResponse<String> handleValidationException(MethodArgumentNotValidException ex) {
        BindingResult result = ex.getBindingResult();
        return CommonResponse.fail(result.getFieldErrors().get(0).getDefaultMessage());
    }

    @ExceptionHandler(Exception.class)
    public CommonResponse handleException(Exception e) {
        // 根据实际业务需求处理异常
        return CommonResponse.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
    }

    /**
     * 处理自定义的业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public CommonResponse<String> handleBusinessException(BusinessException e) {
        return CommonResponse.fail(e.getMessage());
    }
}
